import os
from node import Node
from tree import Tree
import ast
import re
from string import *
from os import listdir
from os.path import isfile, join

class TEDTree:

    def __init__(self, directory):
        self.tree = None
        self.directory = directory
        #fp = open(filename, 'r')
        #self.text = fp.read()

    

    def parseBinaryTree(self, filename):
        fp = open(filename, "r")
        self.text = fp.read()
        root = Node("root", style=Node.ROOT)
        previous = root
        if self.text[0] == "(":
            counter = 0
            for index, item in enumerate(self.text):
                if item == "(":
                    for index2, test in enumerate(self.text[index+1:]):
                        if test == "(" or test == ")":
                            number = self.text[index+1:index+1+index2]
                            node = Node(number, parent=previous, style=Node.NORM)
                            if previous.getChild1() is None:
                                previous.setChild1(node)
                            else:
                                previous.setChild2(node)
                            previous = node
                            break
                    counter = counter + 1
                if item == ")":
                    previous = previous.getParent()
                    counter = counter - 1
                if counter == 0:
                    break
        self.tree = Tree(root)

    def parseNonBinaryTree(self, text):
        root = Node("root", style=Node.ROOT)
        previous = root
        if text[0] == "(":
            counter = 0
            for index, item in enumerate(text):
                if item == "(":
                    for index2, test in enumerate(text[index+1]):
                        if test == "(" or test == ")":
                            number = text[index+1:index+1+index2]
                            node = Node(number, parent=previous, style=Node.NORM)
                            previous.addChild(node)
                            previous = node
                            break
                    counter = counter + 1
                if item == ")":
                    previous = previous.getParent()
                    counter = counter - 1
                if counter == 0:
                    break
        self.tree = Tree(root)
        return

    def createBinaryTree(self, tree, filename):
        fp = open(join(self.directory, filename), 'w')
        root = tree.getRoot().getChild1()
        treeString = self.iterateBinary(root)
        fp.write(treeString)
        fp.close()

    def iterateBinary(self, tree):
        if tree is None:
            return ""
        return "(" + tree.getLabel() + self.iterateBinary(tree.getChild1()) + self.iterateBinary(tree.getChild2()) + ")"

    def createNonBinaryTree(self, tree, filename):
        fp = open(filename, 'w')
        root = tree.getRoot().getChild1()
        treeString = self.iterateNonBinary(root)
        fp.write(treeString)
        fp.close()

    def iterateNonBinary(self, tree):
        if tree is None:
            return ""
        string = "(" + tree.getLabel()
        for node in tree.getChildren():
            string = string + self.iterateNonBinary(node)
        string = string + ")"
        return string
        

    def getTree(self):
        return self.tree

    def parseResults(self, filename):
        results = {}
        fp = open(filename, "r")
        for line in fp:
            if ")" in line:
                line = replace(line, ")", "", 1)
                line = line.strip()
                line = line.split(" ")
                results[line[0]] = {"DMRW":int(line[1]), "Klien":int(line[2]), "Zhang":int(line[3])}
        return results

    def findFilesBinary(self):
        trees = {}
        files = [f for f in listdir(self.directory) if isfile(join(self.directory,f))]
        for filename in files:
            print filename
            if "test" in filename:
                if "G" in filename:
                    number = split(filename, "test", 1)[1]
                    number = split(number, "G.txt", 1)[0]
                    #fp = open(join(self.directory, filename), 'r')
                    self.parseBinaryTree(join(self.directory, filename))
                    tree = self.tree
                    #fp.close()
                    if number not in trees.keys():
                        trees[number] = {"compare":"", "original":""}
                    trees[number]["compare"] = tree
                elif "F" in filename:
                    number = split(filename, "test", 1)[1]
                    number = split(number, "F.txt", 1)[0]
                    #fp = open(join(self.directory, filename), 'r')
                    self.parseBinaryTree(join(self.directory, filename))
                    tree = self.tree
                    #fp.close()
                    if number not in trees.keys():
                        trees[number] = {"compare":"", "original":""}
                    trees[number]["original"] = tree
        return trees

    def findFilesNonBinary(self):
        trees = []
        files = [ f for f in listdir(self.directory) if isfile(join(self.directory,f))]
        for filename in files:
            if "test" in filename:
                fp = open(join(self.directory, filename), 'r')
                self.parseNonBinaryTree(fp.read())
                fp.close()
            elif "results" in filename:
                self.parseResults(join(self.directory, filename))
        
